package chapter1.socket.task.task4;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.*;


public class Server {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("气温", "20°C");
        map.put("风力", "阵风7级");
        map.put("pm2.5", "46");
        map.put("湿度", "95%");
        ServerSocket st = null;
        SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        try {
            st = new ServerSocket(1800);
            System.out.println("服务器启动成功，监听在1800端口");
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        while (true) {
            try {
                Socket s = st.accept();
                new Thread01(s, sim, map).start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}


class Thread01 extends Thread {
    private Socket s;
    private SimpleDateFormat sim;
    private Map<String, String> map;

    public Thread01(Socket s, SimpleDateFormat sim, Map<String, String> map) {
        this.s = s;
        this.sim = sim;
        this.map = map;
    }

    @Override
    public void run() {
        System.out.println(s + "连接成功");
        PrintWriter out;
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
            out = new PrintWriter(s.getOutputStream(), true);

            while (true) {
                String ask = in.readLine();
                if (!map.containsKey(ask))
                    continue;
                out.println(sim.format(new Date()) + " " + map.get(ask));
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (s != null) {
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


